<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { queryCoupons,stopCoupons,delCoupons } from '@/api/Marketing/coupon.js';

const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();

// 新增编辑回退时候刷新列表
onActivated(()=>{
  let closeTagName = sessionStorage.getItem('closeTagName');
  if(closeTagName == 'CouponOrganizeEdit'){ //编辑退回时
      seachTable.value.handlerSearch(); //刷新当前页
      
  }else if(closeTagName == 'CouponOrganizeAdd' || closeTagName == 'CouponOrganizeCopy'){ //新增退回时
      seachTable.value.initSearch(); //返回第一页并刷新
  }
  instance.proxy.$forceUpdate(); //重新渲染demo
  sessionStorage.removeItem('closeTagName'); //溢出缓存中的tag名
})
const formInline = ref([
    {
      type: "input",
      prop: "couponsName",
      placeholder: "优惠券名称",
      label: "",
      model: "",
    },
    {
        type: "select",
        placeholder: "优惠券状态",
        label: '',
        prop: 'couponsStatus',
        data:[
            {
                label:"进行中",
                value:0
            },
            {
                label:"已发完",
                value:1
            },
            {
                label:"已终止",
                value:2
            },
            {
                label:"已失效",
                value:3
            }
        ],
        model: "",
    },
    {
      type: "datePicker",
      prop: ["createTimeStart", "createTimeEnd"],
      startPlaceholder: "开始时间",
      endPlaceholder: "结束时间",
      label: "",
      model: [],
    },
])

const btnLefts = ref([
    {
      label:'新增优惠券',
      type:'primary',
      show:()=>true,
      img:new URL("@/assets/icon/btn-add.png",import.meta.url),
      click:(row)=>{
        router.push({name:'CouponOrganizeAdd'})
      }
    },
])
const btnRights = ref([
])

const tableConfig = ref([

    {
      prop: "couponsName",
      label: "优惠券名称",
      type:"slot",
      slotName:'couponsName',
      width:310
    },
    {
      prop: "couponsRemark",
      label: "备注名称",
      width:200
    },

    // {
    //   prop: "storeInfo",
    //   label: "活动门店",
    //   width:300,
    //   type:"slot",
    //   slotName:'storeInfo',
    // },
    {
      prop: "offerContent",
      label: "优惠内容",
      type:"slot",
      slotName:'offerContent',
      width:310
    },
    {
      prop: "useTime",
      label: "使用时间",
      width:200,
      format:(value,row)=>{
        if(row.usingType == 0){
          return [row.usingStartTime,row.usingEndTime].join("~")
        }else if(row.usingType == 1){
          return `领取后${ row.usingDay || 0 }天内有效`
        }
      }
    },
    {
      prop: "couponsStatus",
      label: "状态",
      width:100,
      format:(value)=>{
        return ["进行中","已发完","已终止","已失效"][value];
      }
    },
    {
      prop: "numShow",
      label: "核销数量/发放数量",
      width:200,
      format:(value,row)=>{
        return `${ row.writeOffNum }/${ row.releaseNum }`
      }
    },
    {
      prop: "releaseTotalNum",
      label: "发放总量",
      width:100
    },
    {
      prop: "createTime",
      label: "创建时间",
      width:200
    },
    {
      type: "action",
      label: "操作",
      width: 320,
      btns: [
        {
          label: () => "复制",
          show:(row)=>{
            return true
          },
          click: async (row) => {
            router.push({name:"CouponOrganizeCopy",query:{id:row.id}})
          },
        },
        {
          label: () => "编辑",
          type:"success",
          show:(row)=>{
            return row.couponsStatus == 0  || row.couponsStatus == 1; 
          },    
          click: async (row) => {
            router.push({name:"CouponOrganizeEdit",query:{id:row.id}})
          },
        },
        {
          label: () => "终止",
          type:"danger",
          show:(row)=>{
            return row.couponsStatus == 0  || row.couponsStatus == 1; 
          },
          click: async (row) => {
            ElMessageBox(
                {
                    confirmButtonText: '终止',
                    confirmButtonClass:'el-button--danger',
                    cancelButtonText: '取消',
                    type: 'warning',
                    title: '提示',
                    showCancelButton: true,
                    message:"确定终止该优惠券？",
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            instance.confirmButtonText = 'Loading...'
                            try{
                                await stopCoupons({couponsId:row.id})
                                instance.confirmButtonLoading = false
                                done();
                                ElMessage.success('终止成功');
                                seachTable.value.handlerSearch();
                            }catch(e){
                                instance.confirmButtonLoading = false
                            }
                        } else {
                            done()
                        }
                    },
                }
            )
          },
        },
        {
          label: () => "删除",
          type:"danger",
          show:(row)=>{

            return false
          },
          click: async (row) => {
            ElMessageBox(
                {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                    title: '提示',
                    confirmButtonClass:'el-button--danger',
                    showCancelButton: true,
                    message:"确定删除该优惠券？",
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            instance.confirmButtonText = 'Loading...'
                            try{
                                await delCoupons({couponsId:row.id})
                                instance.confirmButtonLoading = false
                                done();
                                ElMessage.success('删除成功');
                                seachTable.value.initSearch();
                            }catch(e){
                                instance.confirmButtonLoading = false
                            }
                        } else {
                            done()
                        }
                    },
                }
            )
          },
        },
      ]
    }
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);


const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{
        let result = await queryCoupons(formInline);
 
        totalPage.value = Number(result.total);
        tableData.value = result.records.map(value=>{
          let storeInfo = [];
          value.storeData.forEach(lis=>{
            storeInfo.push(`${ lis.storeName }`) // (${ lis.storeFunctionName.join('/') })
          })
          return {
            ...value,
            storeInfo:storeInfo.join(";")
          }
        })
        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}
const lookDetail = (id)=>{
  router.push({name:'CouponOrganizeDetail',query:{id:id}})
}
</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :forms="formInline"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :totalPage="totalPage"
          @handlerSearch="handlerSearch"
        >
            <template #couponsName="{ row }">
                <div class="a-link" @click="lookDetail(row.id)">{{ row.couponsName }}</div>
            </template>
            <template #offerContent="{ row }">
                <div class="info-show">
                    <div class="text-show" >
                        满{{ `${ row.thresholdAmount?row.thresholdAmount:'' }` }}减{{ `${ row.discountsAmount?row.discountsAmount:'' }` }}
                        
                    </div>
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                              1.优惠内容：满{{ `${ row.thresholdAmount?row.thresholdAmount:'' }` }}减{{ `${ row.discountsAmount?row.discountsAmount:'' }` }}；
                              2.适用门店及业务：{{ row.businessScope  == 0?'全部门店及业务':`指定门店及业务` }}；
                              3.适用范围：{{ ["全部商品可用","指定商品可用","指定商品不可用"][row.activityScope] }}
                            </div>
                        </template>
                        <img src="@/assets/images/warning-circle.png" alt="" class="img">
                    </el-tooltip>

                </div>
            </template>
            <template #storeInfo="{ row }">
                <div class="info-show" v-if="row.businessScope == 1">
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                              {{ row.storeInfo }}
                            </div>
                        </template>
                        <span class="tip-show">
                          {{ row.storeInfo }}
                        </span>
                    </el-tooltip>
                </div>
                <div class="info-show" v-else>
                  全部门店
                </div>
            </template>
        </SeachTable>
    </div>
</template>
<style lang="less" scoped>
.tips-info{
    max-width: 300px; 
}
.info-show{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .tip-show{
        max-width: 100%;
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
    }
    .text-show{
        max-width: calc(100% - 14px);
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        line-height: 18px;
        word-break: break-all;
        word-wrap: break-word;
    }
    .img{
        width: 14px;
        height: 14px;
        cursor: pointer;

    }
}
.a-link{
    color:#3480FF;
    font-size: 14px;
    cursor: pointer;
}

</style>